package com.ruoyi.system.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.Examine;
import com.ruoyi.system.domain.InboundSubsidy;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.vo.FileUploadVO;
import com.ruoyi.system.domain.vo.UnitInformationVO;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.FileUploadService;
import com.ruoyi.system.service.IExamineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.UnitInformationMapper;
import com.ruoyi.system.domain.UnitInformation;
import com.ruoyi.system.service.IUnitInformationService;
import javax.annotation.Resource;
import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * 单位信息Service业务层处理
 *
 * @author zhur
 * @date 2025-04-01
 */
@Service
public class UnitInformationServiceImpl implements IUnitInformationService {
    @Resource
    private UnitInformationMapper unitInformationMapper;


    @Autowired
    private SysUserServiceImpl userService;
    ;

    @Autowired
    private FileUploadService fileUploadService;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

//    @Resource
//    private IExamineService examineService;

    @Resource
    private IExamineService examineService;

    /**
     * 查询单位信息
     *
     * @param id 单位信息主键
     * @return 单位信息
     */
    @Override
    public UnitInformationVO selectUnitInformationById(Long id) {

        UnitInformation unitInformation = unitInformationMapper.selectUnitInformationById(id);
        UnitInformationVO vo = new UnitInformationVO();
        BeanUtils.copyProperties(unitInformation, vo);

        List<FileUploadVO> list = fileUploadService.listFileUploadsByBusinessId(unitInformation.getBusinessId());
        vo.setFiles(list);

        QueryWrapper<Examine> qw = new QueryWrapper<>();
        qw.eq("business_id", unitInformation.getBusinessId());
        qw.orderByDesc("create_time");
        List<Examine> examines = examineService.getBaseMapper().selectList(qw);
        vo.setExamines(examines);
        return vo;

    }

    /**
     * 查询单位信息列表
     *
     * @param unitInformation 单位信息
     * @return 单位信息
     */
    @Override
    public List<UnitInformationVO> selectUnitInformationList(UnitInformation unitInformation) {
        startPage();
        // 构建查询条件
        LambdaQueryWrapper<UnitInformation> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(unitInformation.getUnitName())) {
            queryWrapper.like(UnitInformation::getUnitName, unitInformation.getUnitName());
        }
        if (StringUtils.isNotBlank(unitInformation.getBusinessId())) {
            queryWrapper.eq(UnitInformation::getBusinessId, unitInformation.getBusinessId());
        }
        // 其他查询条件...
        List<UnitInformation> unitList = new ArrayList<>();
        // 查询 UnitInformation 列表
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            unitList = unitInformationMapper.selectList(queryWrapper);
        }else{
            queryWrapper.eq(UnitInformation::getCreateBy, SecurityUtils.getUserId());
            unitList = unitInformationMapper.selectList(queryWrapper);
        }

        // 转换为 VO 并附加文件信息
        List<UnitInformationVO> voList = new ArrayList<>();
        if (unitList.isEmpty()) {
            return voList;
        }

        // 收集所有 businessId
        List<String> businessIds = unitList.stream()
                .map(UnitInformation::getBusinessId)
                .filter(StringUtils::isNotBlank)
                .distinct()
                .collect(Collectors.toList());
        // 批量查询 file_upload 记录
        List<FileUploadVO> fileList = fileUploadService.listFileUploadsByBusinessIds(businessIds);
        // 按 businessId 分组文件
        Map<String, List<FileUploadVO>> fileMap = fileList.stream()
                .collect(Collectors.groupingBy(FileUploadVO::getBusinessId));
        // 组装 VO
        for (UnitInformation unit : unitList) {
            UnitInformationVO vo = new UnitInformationVO();
            BeanUtils.copyProperties(unit, vo);
            vo.setFiles(fileMap.getOrDefault(unit.getId(), new ArrayList<>()));
            QueryWrapper<Examine> qw = new QueryWrapper<>();
            qw.eq("business_id", unit.getBusinessId());
            qw.orderByDesc("create_time");
            List<Examine> examines = examineService.getBaseMapper().selectList(qw);
            vo.setExamines(examines);
            voList.add(vo);
        }
        return voList;
    }

    /**
     * 新增单位信息
     *
     * @param unitInformation 单位信息
     * @return 结果
     */
    @Override
    public AjaxResult insertUnitInformation(UnitInformation unitInformation) {
        unitInformation.setCreateTime(DateUtils.getNowDate());
        unitInformation.setCreateBy(SecurityUtils.getUserId().toString());
        unitInformation.setType("0");
        int i = unitInformationMapper.insert(unitInformation);
        Examine examine = new Examine();
        examine.setStatus(Integer.valueOf(unitInformation.getType()));
        examine.setBusinessId(unitInformation.getBusinessId());
        examine.setCreateBy(SecurityUtils.getUserId().toString());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        examine.setCreateTime(format);
        examine.setRemark(unitInformation.getRemark());
        examineService.insertExamine(examine);
        return i > 0 ? AjaxResult.success() : error();
    }

    /**
     * 修改单位信息
     *
     * @param unitInformation 单位信息
     * @return 结果
     */
    @Override
    public int updateUnitInformation(UnitInformation unitInformation) {
        // 更新用户角色
        if("1".equals(unitInformation.getType())){
           SysUserRole sysUserRole = new SysUserRole();
           sysUserRole.setUserId(Long.valueOf(unitInformation.getCreateBy()));
           sysUserRole.setRoleId(2L);
           List<SysUserRole> batchUserRole = new ArrayList<>();
           batchUserRole.add(sysUserRole);
           sysUserRoleMapper.deleteUserRoleByUserId(sysUserRole.getUserId());
           sysUserRoleMapper.batchUserRole(batchUserRole);
        }
        Examine examine = new Examine();
        examine.setStatus(Integer.valueOf(unitInformation.getType()));
        examine.setBusinessId(unitInformation.getBusinessId());
        examine.setCreateBy(SecurityUtils.getUserId().toString());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        examine.setCreateTime(format);
        examine.setRemark(unitInformation.getRemark());
        examineService.insertExamine(examine);

        return unitInformationMapper.updateById(unitInformation);
    }

    /**
     * 批量删除单位信息
     *
     * @param ids 需要删除的单位信息主键
     * @return 结果
     */
    @Override
    public int deleteUnitInformationByIds(Long[] ids) {
        return unitInformationMapper.deleteUnitInformationByIds(ids);
    }

    /**
     * 删除单位信息信息
     *
     * @param id 单位信息主键
     * @return 结果
     */
    @Override
    public int deleteUnitInformationById(Long id) {
        return unitInformationMapper.deleteUnitInformationById(id);
    }

    @Override
    public String getCurrent() {
        String str = SecurityUtils.getUserId().toString();
        return  unitInformationMapper.selectByCreateBy(str);
    }
}
